//
//  AppDelegate.m
//  quxiangtao
//
//  Created by xbmios on 2018/6/22.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabbarViewController.h"
#import "WelfareViewController.h"
#import "MineViewController.h"
#import "ForumViewController.h"
#import "LJContactManager.h"
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import <AlipaySDK/AlipaySDK.h>
#import <AlibcTradeBiz/AlibcTradeBiz.h>
#import <JDKeplerSDK/JDKeplerSDK.h>
#import "WXApi.h"
#import "WXApiManager.h"
#import "IQKeyboardManager.h"
#import <UMShare/UMShare.h>
#import <UMCommon/UMCommon.h>
#import "HSUpdateApp.h"
#import "TalkingData.h"
#import "TalkingDataEAuth.h"
#import <SobotKit/ZCLibClient.h>
#import <UMPush/UMessage.h>
#import <UMCommon/UMCommon.h>
#import <UMPush/UMessage.h>
#import <UMShare/UMShare.h>
#import <UserNotifications/UserNotifications.h>
#import <UMCommonLog/UMCommonLogHeaders.h>

//#define JDValue_AppKey @"df1c7eb3ebfc40be83bcda479e384608"
//#define JDValue_AppSecret @"7cbb125356344ad9ae2794938dc9667d"

#define JDValue_AppKey @"f3749ed2d7ef4fd3baa6c82a01efddf2"
#define JDValue_AppSecret @"f6dd87a564984faaab4a47c0a2745daa"
@interface AppDelegate ()<UNUserNotificationCenterDelegate>


@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSString *appAnalyticsAppId = @"D35CA1A86A744E358E049A029C53B26F";
    NSString *appAnalyticsChannelId = @"AppStore";
    [TalkingData sessionStarted:appAnalyticsAppId withChannelId:appAnalyticsChannelId];
    [TalkingData backgroundSessionEnabled];
    [TalkingData setExceptionReportEnabled:YES];
    
    // 百川平台基础SDK初始化，加载并初始化各个业务能力插件
    [[AlibcTradeSDK sharedInstance] asyncInitWithSuccess:^{
        
    } failure:^(NSError *error) {
    }];
    
    [[KeplerApiManager sharedKPService] asyncInitSdk:JDValue_AppKey secretKey:JDValue_AppSecret sucessCallback:^{
    } failedCallback:^(NSError *error) {
        NSLog(@"error === %@",error);
    }];
    [KeplerApiManager sharedKPService].isOpenByH5 = YES;

    //智齿SDK
    // 错误日志收集
    [ZCLibClient setZCLibUncaughtExceptionHandler];
    [[ZCLibClient getZCLibClient] initSobotSDK:@"6d075db1d2ff4a8d92f19d0602e24379"];
  
    // 开发阶段打开日志开关，方便排查错误信息
    //默认调试模式打开日志,release关闭,可以不调用下面的函数
    [[AlibcTradeSDK sharedInstance] setDebugLogOpen:YES];
    
    // 设置环境
    [[AlibcTradeSDK sharedInstance] setEnv:AlibcEnvironmentRelease];
    // 设置全局配置，是否强制使用h5
    [[AlibcTradeSDK sharedInstance] setIsForceH5:NO];
    
    /* 设置友盟appkey */
    [UMConfigure initWithAppkey:@"5c6cc08ef1f556fabe000c02" channel:@"App Store"];
    
    [self configUSharePlatforms];
    
    // 微信
    [WXApi startLogByLevel:WXLogLevelNormal logBlock:^(NSString *log) {
        NSLog(@"log : %@", log);
    }];
    
    //向微信注册
    [WXApi registerApp:WxAppID enableMTA:YES];
    
    

    // Override point for customization after application launch.
    //开发者需要显式的调用此函数，日志系统才能工作
    [UMCommonLogManager setUpUMCommonLogManager];
    [UMConfigure setLogEnabled:YES];
   
    //[UMConfigure initWithAppkey:@"5c6cc08ef1f556fabe000c02" channel:@"App Store"];
    
    // Push's basic setting
    UMessageRegisterEntity * entity = [[UMessageRegisterEntity alloc] init];
    //type是对推送的几个参数的选择，可以选择一个或者多个。默认是三个全部打开，即：声音，弹窗，角标
    entity.types = UMessageAuthorizationOptionBadge|UMessageAuthorizationOptionAlert;
    if (@available(iOS 10.0, *)) {
        [UNUserNotificationCenter currentNotificationCenter].delegate=self;
    } else {
        // Fallback on earlier versions
    }
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {

        }else
        {
        }
    }];
    


 
    
    // IQKeyboard
    IQKeyboardManager *manage = [IQKeyboardManager sharedManager];
    manage.enable = YES;
    manage.keyboardDistanceFromTextField = jisuan(30);
    manage.shouldResignOnTouchOutside = YES;
    manage.toolbarDoneBarButtonItemText = @"完成";
    
    // 设置根控制器
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [self chooseRootViewController];
    self.window.backgroundColor = WhiteColor;
    [self.window makeKeyAndVisible];
    
    NSLog(@"%@",self.window.backgroundColor);

    return YES;
    
}

#pragma mark -选择跟控制器
- (UIViewController *)chooseRootViewController {
    
    return [[BaseTabbarViewController alloc] init];
    
}




- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:@"wx68154ea4f566f64b" appSecret:@"879b23930549ec897dcd49748a0ae73e" redirectURL:@"http://mobile.umeng.com/social"];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"1108178011"/*设置QQ平台的appID*/  appSecret:@"CkFcb9O9eAW34ivF" redirectURL:@"http://mobile.umeng.com/social"];
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:@"3352385302"  appSecret:@"e7ffc36edbaa828eb664cc77fa5428a2" redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
    
}


//获取DeviceToken成功
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSLog(@"deviceToken=%@", deviceToken);
}

//iOS10以下使用这两个方法接收通知，
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [UMessage setAutoAlert:NO];
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
        
       
            //定制自定的的弹出框
            if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"标题"
                                                                    message:@"Test On ApplicationStateActive"
                                                                   delegate:self
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
        
                [alertView show];
        
            }
        completionHandler(UIBackgroundFetchResultNewData);
    }
}


//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
    } else {
        // Fallback on earlier versions
    }
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
    }
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    // 阿里百川
    /* 老接口写法 已弃用，建议使用新接口
     if (![[AlibcTradeSDK sharedInstance] handleOpenURL:url]) {
     // 处理其他app跳转到自己的app
     }
     return YES;
     */
    
    // 新接口写法
    if (![[AlibcTradeSDK sharedInstance] application:application
                                             openURL:url
                                   sourceApplication:sourceApplication
                                          annotation:annotation]) {
        // 处理其他app跳转到自己的app
    }
    
    // 支付宝支付
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    [[KeplerApiManager sharedKPService] handleOpenURL:url];
    return YES;
    
}

#pragma 支付回调
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<NSString *, id> *)options {
    
    // 阿里百川
    
    /* 老接口写法 已弃用，建议使用新接口
     if (![[AlibcTradeSDK sharedInstance] handleOpenURL:url]) {
     // 处理其他app跳转到自己的app
     }
     return YES;
     */
    
    // 新接口写法
    if (@available(iOS 9_0, *)) {
        if (![[AlibcTradeSDK sharedInstance] application:application
                                                 openURL:url
                                                 options:options]) {
            //处理其他app跳转到自己的app，如果百川处理过会返回YES
        }
    } else {
        // Fallback on earlier versions
    
    }
    
    
    // 支付宝支付
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        
//        //把KYAlertView 由1秒改成2.5
//        [[KYAlertView sharedInstance]showAlertViewWithMessage:@"支付成功，请去我的订单查看"];
    }
    
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }

    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    [[KeplerApiManager sharedKPService] handleOpenURL:url];
    return YES;
    
}



- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
    }
    
    [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
   
}


- (void)applicationDidEnterBackground:(UIApplication *)application {

}


- (void)applicationWillEnterForeground:(UIApplication *)application {

}


- (void)applicationDidBecomeActive:(UIApplication *)application {

}

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}



- (void)applicationWillTerminate:(UIApplication *)application {
    [[NSUserDefaults standardUserDefaults] setObject:@"qqqq" forKey:@"popView"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}



@end
